package com.ddz.service;

import com.ddz.model.LoginMessage;
import com.ddz.model.enums.SystemEnums;
import com.ddz.util.JDBCUtil;
import com.ddz.util.StringUtil;
import org.json.JSONObject;

import java.sql.ResultSet;
import java.sql.SQLException;

public class UserloginService {
    private LoginMessage loginMessage;

    public UserloginService() {
        loginMessage = new LoginMessage();
    }

    /**
     * 判断用户账号和密码是否正确，并判断玩家是否已经登录并返回消息
     *
     * @param userID
     * @param password
     * @return LoginMessage
     */
    public LoginMessage Login(String userID, String password) {
        JSONObject json = new JSONObject();
        if (StringUtil.isEmpty(userID)) {
            loginMessage.setStatus(100);
            loginMessage.setMsg("登录失败！账号为空！");
            loginMessage.setJsonObject(json);
        } else if (StringUtil.isEmpty(password)) {
            loginMessage.setStatus(100);
            loginMessage.setMsg("登录失败！密码为空！");
            loginMessage.setJsonObject(json);
        } else if (StringUtil.isOver100(userID)) {
            loginMessage.setStatus(100);
            loginMessage.setMsg("登录失败！账号超过100字符！");
            loginMessage.setJsonObject(json);
        } else if (StringUtil.isOver100(password)) {
            loginMessage.setStatus(100);
            loginMessage.setMsg("登录失败！密码超过100字符！");
            loginMessage.setJsonObject(json);
        }
        json.put("userID", userID);
        json.put("password", password);
        try {
            JDBCUtil.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        String sql = "SELECT * FROM " + SystemEnums.SQL_TABLE_USER.getValue() + " WHERE userId =? AND password =?";
        ResultSet resultSet = JDBCUtil.executeQuery(sql, json.getString("userID"), json.getString("password"));
        try {
            if (resultSet.next()) {
                loginMessage.setStatus(200);
                loginMessage.setMsg("登录成功！");
                json.put("nickname", resultSet.getString("nickname"));
                json.put("score", resultSet.getInt("score"));
                loginMessage.setJsonObject(json);
            } else {
                loginMessage.setStatus(100);
                loginMessage.setMsg("登录失败！账号或密码错误！");
                loginMessage.setJsonObject(json);
            }
        } catch (SQLException e) {
            System.out.println("SQL语句异常:" + e.getMessage());
            throw new RuntimeException(e);
        }

        return loginMessage;
    }
}
